// index page
// ============

define([ 'require', 'zepto', 'utils', 'wxpay', 'sui', 'countDown' ],
  function(require, $, utils, wxpay) {
  return {
    init : function(data) {
    this.data = data;
    this.initPage()
    this.token = null;
    },
    
    initPage : function() {
    var that = this;
    
    var $mobile = $("input[name='mobile']");
    
    $(document).on("click", ".registration-form .pay-btn",function(e) {
      e.preventDefault();
      
      if (that.data.orderId) {
          if (that.data.microMessenger === 'true') {
            that.requestWxPay(that.data.orderId)
            return;
          } else {
            window.location.href = window.__CTX__.root + '/alipay/start?orderId=' + that.data.orderId + '&returnUrl=123';
            return;
          }
        }
          
          var name = $("input[name='name']").val().trim();
          var gender = $("input[name='gender']:checked").val();
          var wechat = $("input[name='wechat']").val().trim();
          var mobile = $mobile.val().trim();
          
          if (!name) {
              $.toast("请填写您的称呼姓名")
              return false;
            } else if (!gender) {
              $.toast("请选择性别");
              return false;
            } else if (!mobile) {
              $.toast("请填写手机号");
              return false;
            } else if (mobile && !that.isMobile(mobile)) {
              $.toast("请填写请正确的手机号");
              return false;
            }
          
          if (!that.data.bmiQuestionId) {
            var age = $("input[name='age']").val().trim();
            var height = $("input[name='height']").val().trim();
            var weight = $("input[name='weight']").val().trim();
            
            if (!age) {
              $.toast("请填写您的年龄")
              return false;
            } else if (!/^[1-9]\d*$/.test(age)) {
              $.toast("请填写正确格式的年龄")
              return false;
            } else if (!height) {
              $.toast("请填写您的身高");
              return false;
            } else if (height > 230 || height < 100) {
              $.toast("抱歉，您的身高未在测试范围 100-230cm");
              return false;
            } else if (!weight) {
              $.toast("请填写您的体重 ");
              return false;
            } else if (weight > 200 || weight < 30) {
              $.toast("抱歉，您的体重未在测试范围 30-200kg");
              return false;
            }
          }
          
          var parameters = $(".registration-form").serializeArray();
          
          if (that.data.bmiQuestionId) {
            parameters.push({
              "name" : "bmiQuestionId",
              "value" : that.data.bmiQuestionId
            });
          }
          
          parameters.push({
            "name" : "token",
            "value" : that.token
          });
          
          $.ajax({
          url : window.__CTX__.root + '/taste/sign-up',
          type : 'POST',
          data : parameters,
          dataType : "json",
          success : function(data) {
            if (data.code == 0) {
                var orderId = data.data.orderId;
                var userId = data.data.userId;
                  
                  if (orderId && userId) {
                    if (that.data.microMessenger === 'true') {
                      that.requestWxPay(orderId, userId)
                    } else {
                      window.location.href = window.__CTX__.root + '/alipay/start?orderId=' + orderId + '&userId=' + userId;
                    }
                  } else {
                    $.toast("订单生成失败");
                  }
                } else {
            }
          },
          
          error : function() {
            $.toast("加载失败");
          }
          })
        })
      },

      /**
       * Check mobile value is valid or not
       */
      isMobile : function(mobile) {
        return mobile && /^((13)|(15)|(17)|(18))\d{9}$/.test(mobile)
      },
      
      /**
       * Request server to send verifiy code to mobile
       */
      requestVerifyCode: function(mobile, success, failure) {
        $.showIndicator()
        utils.requestVerifyCode(mobile, function(result) {
          $.hideIndicator()
          $.toast('验证码发送成功')
          success && success(result.data)
        }, failure)
      },
      
      /**
       * Request server to prepare WeChat payment data
       */
      requestWxPay : function(orderId, userId) {
    	$.showPreloader('正在提交支付数据')
    	
    	var that = this
    	
    	$.ajax({
    	  type : 'POST',
          url : __CTX__.root + '/wxpay/prepare',
          data : {
            'orderId' : orderId,
            'userId' : userId,
            'currentUrl' : location.href.split('#')[0]
          }
        }).done(
          function(response) {
        	$.hidePreloader()
        	utils.processResult(response, that.configWxPay.bind(that), function(result) {
              $.toast(result.message || '请求支付数据失败')
            })
          })
        },

        /**
         * Handle success WeChat pay, config WeChat JS SDK and invoke
         * pay
         */
        configWxPay : function(result) {
          var that = this
          jsConfig = result.data.jsConfig, 
          payConfig = result.data.payConfig

          wxpay.injectConfig(jsConfig, [ 'chooseWXPay' ])
          wxpay.invokePay(payConfig, function(res) {
            $.toast('支付成功，正在为您跳转')
            setTimeout(function() {
              location.href = __CTX__.root + "/taste/sign-up/success";
            }, 1000)
          })
  }
  }
})